package com.gallery.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.gallery.exceptions.AIException;
import com.gallery.result.Result;
import com.gallery.service.IQuestionService;
import com.gallery.utils.AIUtil;
import dto.AIImageQuestionDTO;
import dto.AITalkDTO;
import entity.Questions;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.time.LocalDateTime;

/**
 * @param
 * @return
 */
@RequestMapping("/ai")
@RestController
@RequiredArgsConstructor
@Slf4j
public class AIController {
    private final AIUtil aiUtil;
    private final IQuestionService questionService;
    /**
     * ai文字问答接口
     * @return
     */
    @PutMapping("/question")
    public Result<String>talk(AITalkDTO aiTalkDTO){
        Long userId = StpUtil.getLoginIdAsLong();
        String ans;
        try {
             ans = aiUtil.aiTalk(aiTalkDTO.getMsg(), aiTalkDTO.getModel());
        }catch (Exception e){
            throw new AIException("AI接口请求失败！请稍后重试qwq");
        }
        //存入数据库
        Questions questions =new Questions();
        questions.setQuestion(aiTalkDTO.getMsg());
        questions.setCreateTime(LocalDateTime.now());
        questions.setAnswer(ans);
        questions.setUserId(userId);
        questionService.save(questions);
        return Result.success(ans);
    }

    @PutMapping("/imagesQuestion")
    public Result<String> getBaiduPictureImageAi(AIImageQuestionDTO aiImageQuestionDTO) throws IOException, InterruptedException {
        log.info("收到请求");
        String taskid = aiUtil.putPictureMessage(aiImageQuestionDTO.getFile(), aiImageQuestionDTO.getMsg());
        //5s等待百度处理结果
        Thread.sleep(5000);
        String ans = aiUtil.getPictureAns(taskid);
        return Result.success(ans);
    }

}
